/**
 * 设施点位数据操作API
 * 用于管理地图上的设施点位
 */

import { hospitalDB, FacilityData } from '../indexedDB'

export interface CreateFacilityRequest {
  attractionId: string
  floorId?: string
  name: string
  type: 'toilet' | 'atm' | 'info' | 'parking' | 'entrance' | 'exit' | 'emergency' | 'wifi' | 'charging'
  position: [number, number]
  description?: string
  status?: 'active' | 'inactive' | 'maintenance'
  metadata?: Record<string, any>
}

export interface UpdateFacilityRequest extends Partial<CreateFacilityRequest> {
  id: string
}

export interface FacilityResponse {
  success: boolean
  msg: string
  data?: FacilityData
}

export interface FacilitiesListResponse {
  success: boolean
  msg: string
  data?: FacilityData[]
}

/**
 * 创建设施点位
 */
export const createFacility = async (
  facility: CreateFacilityRequest
): Promise<FacilityResponse> => {
  try {
    const data = await hospitalDB.addFacility({
      ...facility,
      status: facility.status || 'active',
      metadata: facility.metadata || {}
    })
    
    return {
      success: true,
      msg: '设施点位创建成功',
      data
    }
  } catch (error) {
    console.error('创建设施点位失败:', error)
    return {
      success: false,
      msg: '创建设施点位失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据景区ID获取设施列表
 */
export const getFacilitiesByAttraction = async (
  attractionId: string
): Promise<FacilitiesListResponse> => {
  try {
    // 暂时使用示例数据，根据不同景区返回不同设施
    let data: any[] = []
    
    if (attractionId === 'attraction_1') { // 西湖风景区
      data = [
        {
          id: 'facility_1_1',
          name: '断桥观景台',
          attractionId: 'attraction_1',
          facilityType: 'viewing',
          position: [120.1571, 30.2761],
          status: 'active',
          description: '断桥残雪观景点，冬季雪景美不胜收',
          capacity: 200,
          amenities: ['观景台', '休息座椅', '拍照区'],
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        },
        {
          id: 'facility_1_2',
          name: '西湖游船码头',
          attractionId: 'attraction_1',
          facilityType: 'transportation',
          position: [120.1531, 30.2721],
          status: 'active',
          description: '西湖游船停靠码头',
          capacity: 50,
          amenities: ['游船服务', '等候区', '购票亭'],
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        },
        {
          id: 'facility_1_3',
          name: '苏堤春晓入口',
          attractionId: 'attraction_1',
          facilityType: 'entrance',
          position: [120.1491, 30.2401],
          status: 'active',
          description: '苏堤景区主要入口',
          capacity: 500,
          amenities: ['入口检票', '游客咨询', '卫生间'],
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        }
      ]
    } else if (attractionId === 'attraction_2') { // 雷峰塔景区
      data = [
        {
          id: 'facility_2_1',
          name: '雷峰塔观光电梯',
          attractionId: 'attraction_2',
          facilityType: 'transportation',
          position: [120.1495, 30.2313],
          status: 'active',
          description: '通往塔顶的观光电梯',
          capacity: 12,
          amenities: ['观光电梯', '导览系统'],
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        },
        {
          id: 'facility_2_2',
          name: '雷峰塔文化展览馆',
          attractionId: 'attraction_2',
          facilityType: 'exhibition',
          position: [120.1485, 30.2303],
          status: 'active',
          description: '展示雷峰塔历史文化',
          capacity: 100,
          amenities: ['文物展示', '多媒体介绍', '休息区'],
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        }
      ]
    } else if (attractionId === 'attraction_3') { // 湖滨商业区
      data = [
        {
          id: 'facility_3_1',
          name: '湖滨步行街',
          attractionId: 'attraction_3',
          facilityType: 'walkway',
          position: [120.1606, 30.2594],
          status: 'active',
          description: '主要商业步行街道',
          capacity: 1000,
          amenities: ['步行街', '街头艺人表演', '座椅休息'],
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        },
        {
          id: 'facility_3_2',
          name: '音乐喷泉广场',
          attractionId: 'attraction_3',
          facilityType: 'entertainment',
          position: [120.1596, 30.2574],
          status: 'active',
          description: '大型音乐喷泉表演广场',
          capacity: 800,
          amenities: ['音乐喷泉', '观赏座椅', '表演舞台'],
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        },
        {
          id: 'facility_3_3',
          name: '地下停车场',
          attractionId: 'attraction_3',
          facilityType: 'parking',
          position: [120.1586, 30.2584],
          status: 'active',
          description: '湖滨商业区地下停车场',
          capacity: 500,
          amenities: ['车位', '电梯', '收费系统'],
          createdAt: new Date('2023-01-01'),
          updatedAt: new Date()
        }
      ]
    }
    
    return {
      success: true,
      msg: '获取设施列表成功',
      data
    }
  } catch (error) {
    console.error('获取设施列表失败:', error)
    return {
      success: false,
      msg: '获取设施列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据楼层ID获取设施列表
 */
export const getFacilitiesByFloor = async (
  floorId: string
): Promise<FacilitiesListResponse> => {
  try {
    const data = await hospitalDB.getFacilitiesByFloor(floorId)
    return {
      success: true,
      msg: '获取楼层设施列表成功',
      data
    }
  } catch (error) {
    console.error('获取楼层设施列表失败:', error)
    return {
      success: false,
      msg: '获取楼层设施列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 更新设施信息
 */
export const updateFacility = async (
  id: string,
  updates: Partial<CreateFacilityRequest>
): Promise<FacilityResponse> => {
  try {
    // 先获取现有数据
    const existing = await hospitalDB.getFacility?.(id)
    if (!existing) {
      return {
        success: false,
        msg: '设施不存在'
      }
    }
    
    // 合并更新数据
    const updatedData: FacilityData = {
      ...existing,
      ...updates,
      id,
      updatedAt: new Date()
    }
    
    await hospitalDB.updateFacility(updatedData)
    
    return {
      success: true,
      msg: '设施更新成功',
      data: updatedData
    }
  } catch (error) {
    console.error('更新设施失败:', error)
    return {
      success: false,
      msg: '更新设施失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 删除设施
 */
export const deleteFacility = async (id: string): Promise<FacilityResponse> => {
  try {
    await hospitalDB.deleteFacility(id)
    return {
      success: true,
      msg: '设施删除成功'
    }
  } catch (error) {
    console.error('删除设施失败:', error)
    return {
      success: false,
      msg: '删除设施失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 设施类型配置
 */
export const getFacilityTypes = () => {
  return [
    { 
      type: 'toilet', 
      label: '卫生间', 
      icon: '🚻', 
      color: '#06b6d4',
      description: '公共卫生间'
    },
    { 
      type: 'atm', 
      label: 'ATM机', 
      icon: '🏧', 
      color: '#10b981',
      description: '自动取款机'
    },
    { 
      type: 'info', 
      label: '咨询台', 
      icon: 'ℹ️', 
      color: '#3b82f6',
      description: '信息咨询服务台'
    },
    { 
      type: 'parking', 
      label: '停车场', 
      icon: '🅿️', 
      color: '#8b5cf6',
      description: '停车区域'
    },
    { 
      type: 'entrance', 
      label: '入口', 
      icon: '🚪', 
      color: '#10b981',
      description: '主要入口'
    },
    { 
      type: 'exit', 
      label: '出口', 
      icon: '🚶', 
      color: '#f59e0b',
      description: '安全出口'
    },
    { 
      type: 'emergency', 
      label: '紧急服务', 
      icon: '🚨', 
      color: '#ef4444',
      description: '紧急服务点'
    },
    { 
      type: 'wifi', 
      label: 'WiFi热点', 
      icon: '📶', 
      color: '#6b7280',
      description: '无线网络接入点'
    },
    { 
      type: 'charging', 
      label: '充电站', 
      icon: '🔌', 
      color: '#f59e0b',
      description: '手机充电服务'
    }
  ]
}

/**
 * 设施状态选项
 */
export const getFacilityStatusOptions = () => {
  return [
    { label: '正常使用', value: 'active', color: '#10b981' },
    { label: '暂停使用', value: 'inactive', color: '#f59e0b' },
    { label: '维护中', value: 'maintenance', color: '#ef4444' }
  ]
}